/**
 * fulihui.com Inc.
 * Copyright (c) 2015-2017 All Rights Reserved.
 */
package com.fulihui.information.service;

import com.alibaba.fastjson.JSON;
import com.fulihui.accountcore.api.UserAccountsService;
import com.fulihui.accountcore.enums.ProductType;
import com.fulihui.accountcore.enums.UserAccountTypeEnum;
import com.fulihui.accountcore.enums.UserAccountUnitEnum;
import com.fulihui.accountcore.request.useraccount.UserAccountsAmountRequest;
import com.fulihui.information.api.AwardService;
import com.fulihui.information.dal.dataobj.InfoUserBehaviorReward;
import com.fulihui.information.dal.dataobj.InfoUserBehaviorRewardExample;
import com.fulihui.information.dal.mapper.InfoUserBehaviorRewardMapper;
import com.fulihui.information.enums.AwardType;
import com.fulihui.information.enums.RewardedType;
import com.fulihui.information.model.UserRegisterAwardParam;
import com.fulihui.information.request.NewUserReadAwardRequest;
import com.fulihui.information.result.NewUserReadAwardResult;
import com.fulihui.integral.core.api.ISBaseRuleService;
import com.fulihui.integral.core.common.constants.RuleKeys;
import com.fulihui.integral.core.common.entity.RuleData;
import com.fulihui.integral.core.dto.ISBaseRuleDTO;
import com.fulihui.integral.core.enums.ISChannelType;
import com.fulihui.integral.core.enums.ISRuleSwitchType;
import com.fulihui.integral.core.request.ISBaseRuleQueryReq;
import com.fulihui.integral.core.result.ISBaseRuleResult;
import org.near.servicesupport.result.ResultBuilder;
import org.near.servicesupport.result.TSingleResult;
import org.near.servicesupport.util.ConditionValidator;
import org.near.toolkit.common.StringUtil;
import org.near.toolkit.security.codec.DESCoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 奖励服务
 * @author: Levon
 * @version: v 0.1 2017-06-12 11:26
 */
@Service("awardService")
public class AwardServiceImpl implements AwardService{

    private static final Logger logger = LoggerFactory.getLogger(AwardServiceImpl.class);

    private final static String DES_KEY = "SelJaqsOwTifr4krRaxibBf7";

    @Autowired
    InfoUserBehaviorRewardMapper infoUserBehaviorRewardMapper;
    @Autowired
    UserAccountsService userAccountsService;
    @Autowired
    ISBaseRuleService iSBaseRuleService;

    /**
     * 新用户阅读奖励
     *
     * @param request
     * @return
     */
    @Override
    public NewUserReadAwardResult userRegisterAward(NewUserReadAwardRequest request) {
        ConditionValidator.validate(request);

        logger.info("user register award is bengin!request={}",request);

        // TODO 由于开发时间紧张，此处开关沿用积分的开关配置
        ISBaseRuleQueryReq req = new ISBaseRuleQueryReq();
        req.setChannel(ISChannelType.REGISTER_CASH.getCode());
        ISBaseRuleResult ruleResult = iSBaseRuleService.queryISRuleByChannel(req);
        if(ruleResult == null || ruleResult.getIsBaseRuleDTO() == null){
            return ResultBuilder.fail(NewUserReadAwardResult.class,1010,"No setting rules!");
        }

        //判断开关是否开启
        ISBaseRuleDTO ruleinfo = ruleResult.getIsBaseRuleDTO();
        String ruleSwitch = ruleinfo.getRuleSwitch();
        if(StringUtil.isBlank(ruleSwitch) || StringUtil.equals(ruleSwitch, ISRuleSwitchType.OFF.getCode())){
            return ResultBuilder.fail(NewUserReadAwardResult.class,1008,"The registered award switch is closed!");
        }

        //是否有设置奖励规则
        Map<String, RuleData> ruleDataMap = ruleinfo.getRuleData();
        RuleData ruleData = ruleDataMap.get(RuleKeys.REGISTER_CASH);
        if(ruleData == null || StringUtil.isBlank(ruleData.getProperty())){
            return ResultBuilder.fail(NewUserReadAwardResult.class,1011,"No rewards are set!");
        }

        Long awardAmount = Long.valueOf(ruleData.getValue());

        // 开始解密参数
        String param = request.getParam();
        if(StringUtil.isBlank(param)){
            return ResultBuilder.fail(NewUserReadAwardResult.class,1001,"param must not be null!");
        }

        UserRegisterAwardParam awardParam = null;
        try {
            //参数解密
            String decryptParam = DESCoder.decrypt(param, DES_KEY);
            awardParam = JSON.parseObject(decryptParam, UserRegisterAwardParam.class);
        }catch (Exception e){
            logger.error("param decrypt is error,param={},error={}",param,e.getMessage());
            return ResultBuilder.fail(NewUserReadAwardResult.class,1002,"parameter decryption failure!");
        }

        if(awardParam == null){
            return ResultBuilder.fail(NewUserReadAwardResult.class,1003,"parse json param is error,param is null!");
        }

        // 验证用户阅读的资讯数
        List<String> infoids = awardParam.getInfoids();
        if(CollectionUtils.isEmpty(infoids) || infoids.size() < 10){
            return ResultBuilder.fail(NewUserReadAwardResult.class,1004,"infoids is empty or length < 10!");
        }

        // 拿到userid
        String userid = awardParam.getUserid();
        if(StringUtil.isBlank(userid)){
            return ResultBuilder.fail(NewUserReadAwardResult.class,1005,"userId must not be null!");
        }

        //查询是否满足赠送条件
        InfoUserBehaviorRewardExample example = new InfoUserBehaviorRewardExample();
        InfoUserBehaviorRewardExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userid);
        criteria.andRTypeEqualTo(AwardType.REGISTER_CASH.getCode());
        List<InfoUserBehaviorReward> infoUserBehaviorRewards = infoUserBehaviorRewardMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(infoUserBehaviorRewards)){
            return ResultBuilder.fail(NewUserReadAwardResult.class,1006,"Is not a new user, ignore!");
        }

        //验证是否给这个用户送过钱了
        InfoUserBehaviorReward infoUserBehaviorReward = infoUserBehaviorRewards.get(0);
        Long amount = infoUserBehaviorReward.getAmount();
        Integer isRewarded = infoUserBehaviorReward.getIsRewarded();
        if(amount > 0L && RewardedType.REWARDED_TRUE.getFlag() == isRewarded){
            return ResultBuilder.fail(NewUserReadAwardResult.class,1007,"The user has already handed out awards!");
        }

        //打赏
        return reward(userid,awardAmount);
    }

    private NewUserReadAwardResult reward(String userId,Long amount){
        logger.info("给满足条件的新注册用户{}打赏,数额={}",userId,amount);
        UserAccountsAmountRequest request = new UserAccountsAmountRequest();
        request.setUserId(userId);
        request.setAccountType(UserAccountTypeEnum.CASH.getCode());
        request.setAmount(amount);
        request.setUnit(UserAccountUnitEnum.FEN.getCode());
        request.setReason("新用户奖励");
        request.setReasonMark(ProductType.REGISTER_ACTIVITY.getCode());
        request.setOutTradeNo(UUID.randomUUID().toString().replace("-",""));
        request.genKey();
        TSingleResult<Boolean> result = userAccountsService.addAmount(request);
        if(result != null && result.getValue() == true){
            //修改标识
            InfoUserBehaviorReward record = new InfoUserBehaviorReward();
            record.setIsRewarded(RewardedType.REWARDED_TRUE.getFlag());
            record.setAmount(amount);
            InfoUserBehaviorRewardExample example = new InfoUserBehaviorRewardExample();
            InfoUserBehaviorRewardExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andRTypeEqualTo(AwardType.REGISTER_CASH.getCode());
            infoUserBehaviorRewardMapper.updateByExampleSelective(record,example);
            NewUserReadAwardResult awardResult = ResultBuilder.succ(NewUserReadAwardResult.class);
            awardResult.setValue(amount);
            return awardResult;
        }else{
            logger.info("{}打赏失败了，result={}",userId,result);
            return ResultBuilder.fail(NewUserReadAwardResult.class,result.getErrcode(),result.getErrmsg());
        }
    }

}
